package com.winit.emListener.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by wanglin on 2017/7/19.
 */
public class EmJobService implements MessageListener {

    private static Logger logger = LoggerFactory.getLogger(EmJobService.class);


    private RestTemplate restTemplate = new RestTemplate();

    private static Gson gson=new Gson();
    @Override
    public void onMessage(Message message){
        try{
            logger.info("com.winit.upush.emPush.service.EmPushJobService.onMessage");

            logger.info("Headers="+message.getMessageProperties().getHeaders());


            String messageType = message.getMessageProperties().getHeaders().get("messageType").toString();
            logger.info("messageType="+messageType);

            String appid = message.getMessageProperties().getHeaders().get("fromAppId").toString();
            logger.info("appid="+appid);
            String msg=new String(message.getBody());

            JsonObject body = gson.fromJson(msg, JsonObject.class);
            JsonObject headers= body.get("headers").getAsJsonObject();
            String eventType=  headers.get("eventType").getAsString();
            System.out.println(eventType);
            System.out.println(headers.get("module").getAsString());
            try {
                JsonObject payload = body.get("payload").getAsJsonObject();
                JSONObject json = JSONObject.parseObject(payload.toString());
                json=parseJsonString(json);
                System.out.println(json);
            }catch (Exception e){
                System.out.println(e.getMessage());

            }
        }catch (Exception e){
            logger.error("消息异常:"+e.getMessage());
        }
    }



    /**
     * @描述 将json字符串解析为map
     * @author 曾泽亦
     */
    public static JSONObject parseJsonString(JSONObject jsonObject){
        String jsonStr = jsonObject.toJSONString();
        if(jsonStr.contains("@type")){
            jsonStr=jsonStr.replaceAll("@type","modelType");
        }
        JSONObject json = new JSONObject();
        LinkedTreeMap<String, Object> jsonMap = JSONObject.parseObject(jsonStr, new TypeReference<LinkedTreeMap<String, Object>>() {
        });
        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            if(entry.getValue() instanceof Map){
                json.put(entry.getKey(),parseJsonString((JSONObject) entry.getValue()));
            }else if(entry.getValue() instanceof List){
                json.put(entry.getKey(),parseJsonString((JSONArray) entry.getValue()));
            }else{
                if(!"modelType".equals(entry.getKey())){
                    json.put(entry.getKey(),"");
                }else{
                    json.put(entry.getKey(),entry.getValue());
                }
            }
        }
        json=JSONObject.parseObject(json.toJSONString().replaceAll("modelType","@type")) ;
        return json;
    }

    public static List<Object> parseJsonString(JSONArray jsonArray){
        List<Object> jsons = new ArrayList<Object>();
        for(int i=0;i<jsonArray.size();i++){
            if(jsonArray.get(i) instanceof Map){
                JSONObject jsonObject= (JSONObject) jsonArray.get(i);
                jsons.add(parseJsonString(jsonObject));
            }

        }
        return jsons;
    }

    public static void main(String[] args) {
        String str="{\"type\":\"com.winit.core.event.UmsContactEvent\",\"contactId\":41033,\"contactJobDes\":\"logisitc department manage\",\"contactJobTitle\":\"logisitc department manage\",\"contactWechat\":\"23\",\"customerId\":\"1000019\",\"customerName\":\"Winit (UK)\",\"email\":\"test40@winit.company\",\"mobile\":\"1345566\",\"name\":\"张三\",\"recommenderEmail\":\"\",\"saler\":\"吴兰兰\"}";
        JSONObject json = JSONObject.parseObject(str);
        System.out.println(parseJsonString(json));
    }
}







